package com.smart.thirteen.call;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.*;
import org.springframework.web.servlet.tags.Param;

import java.sql.CallableStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;

/**
 * @author junrui.wang
 * @create 2019/10/21
 */
public class CallableStatementCreatorTest {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath*:com/smart/thirteen/applicationContext-template.xml");
        JdbcTemplate jdbcTemplate = (JdbcTemplate) ac.getBean("jdbcTemplate");

        String callString = "{call P_GET_TOPIC_NUM(?, ?)}";

        String userID = "1111";

        //通过CallableStatementCreatorFactory创建CallableStatementCreator
        CallableStatementCreatorFactory factory = new CallableStatementCreatorFactory(callString);
        factory.addParameter(new SqlParameter("user_id", Types.VARCHAR));
        factory.addParameter(new SqlOutParameter("topic_num", Types.INTEGER));
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("user_id", userID);
        CallableStatementCreator creator = factory.newCallableStatementCreator(paramMap);

        Integer num = jdbcTemplate.execute(creator, new CallableStatementCallback<Integer>() {
            @Override
            public Integer doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
                cs.execute();
                return cs.getInt(2);
            }
        });

        System.out.println(num);
    }
}
